package cn.kgc.vue.controller;

import cn.kgc.vue.annotation.LogAnnotation;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Permission;
import cn.kgc.vue.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import cn.kgc.vue.enums.OperationType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@RestController
@RequestMapping("permission")
@Api(tags = "权限模块")
public class PermissionController {

@Resource
private PermissionService permissionService;

    @GetMapping("tree")
    @ApiOperation("树权限列表")
    public ResponseResult tree() {
        LambdaQueryWrapper<Permission> lambda = new QueryWrapper<Permission>().lambda();
        lambda.select(Permission::getId,Permission::getPid,Permission::getTitle,Permission::getIsMenu);
        List<Permission> list = permissionService.list(lambda);
        return ResponseResult.success().data("permissionList",list);
    }

    @GetMapping("list")
    @ApiOperation("权限列表")
    public ResponseResult list() {
        List<Permission> list = permissionService.list();
        return ResponseResult.success().data("permissionList",list);
    }

    @LogAnnotation(model="权限模块",operation= OperationType.ADD)
    @RequiresPermissions("sys:auth:add")
       @PostMapping("add")
    @ApiOperation("新增权限")
    public ResponseResult add(@RequestBody Permission permission) {
        permissionService.saveOrUpdate(permission);
        return ResponseResult.success().message("权限添加成功");
    }


    @GetMapping("getOne/{id}")
    @ApiOperation("获取一个权限信息")
    public ResponseResult getOnePermission(@PathVariable("id") Integer id) {
        Permission permission = permissionService.getById(id);
        Integer pid = permission.getPid();
        // 获取父菜单的title
        String title = "";
        Permission permission2 = permissionService.getById(pid);
        if (ObjectUtils.isNotNull(permission2)){
            title= permission2.getTitle();
        }

        return  ResponseResult.success().data("permission",permission).data("parentTitle",title);
    }

    @LogAnnotation(model="权限模块",operation= OperationType.DELETE)
    @RequiresPermissions("sys:auth:delete")
    @DeleteMapping("delete/{id}")
    @ApiOperation("删除一个权限")
    public ResponseResult deletePermission(@PathVariable("id") Integer id) {


        return  permissionService.deletePermission(id);
    }




}
